/*
* @Author: sean
* @Date:   2019-12-18 10:54:23
* @Last Modified by:   sean
* @Last Modified time: 2019-12-18 10:54:25
*/
const fs = require('fs');

class build {
    test() {
        let d = require(ROOT_DIR + DS + "api/config.json")
        let a = to_mkdir(ROOT_DIR + DS + "api/bb.json", to_json(d), true, true)
        if (a) {
            return fs.readdirSync(ROOT_DIR + DS + "api")
        } else {
            const f
            return 111
        }
    }
    /**
     * 添加页面集
     * @return {[type]} [description]
     */
    page_group_add() {
        try {
            let path = ROOT_DIR + DS + "pages" + DS + $_POST.path;
            if ($_POST.path == 'index' || is_dir(path)) {
                throw new Exception('不可添加', 40001);
            }

            return mkdir(path);

        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 删除页面集
     * @return {[type]} [description]
     */
    page_group_del() {
        try {
            let path = ROOT_DIR + DS + "pages" + DS + $_POST.path;
            let check = fs.readdirSync(path);
            if (empty(check)) {
                return delDir(path);
            } else {
                throw new Exception('存在页面不可删除', 10001);
            }

        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 获取文件列表
     * @return {[type]} [description]
     */
    page_group_all() {
        try {
            let path = ROOT_DIR + DS + "pages";
            let data = fs.readdirSync(path);
            let result = [];
            if (data) {

                data.forEach(function(value, key) {
                    if (value != 'index.vue') {
                        result.push(value);
                    }
                })
            }

            return result;
        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 检测页面名是否可用
     * @return {[type]} [description]
     */
    page_check() {
        try {
            let path = ROOT_DIR + DS + "pages" + DS + $_POST.path + DS + $_POST.name + '.json';
            if ($_POST.name == 'index' || is_dir(path)) {
                throw new Exception('页面名已不可用', 40001);
            } else {
                return true;
            }

        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 保存页面
     * @return {[type]} [description]
     */
    page_save() {
        try {
            let path = ROOT_DIR + DS + "pages" + DS + $_POST.data.config.data.path + DS + $_POST.data.config.data.name + '.json';

            return to_mkdir(path, to_json($_POST.data), true, true);

        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 获取页面
     * @return {[type]} [description]
     */
    page_all() {
        try {
            let path = ROOT_DIR + DS + "pages";
            let data = fs.readdirSync(path);
            let result = [];

            for (var i = 0; i < data.length; i++) {
                if (data[i] != 'index.vue') {
                    let info = {
                        label: data[i],
                        name: data[i],
                        children: []
                    }

                    let page_list = fs.readdirSync(path + DS + data[i]);
                    for (var j = 0; j < page_list.length; j++) {
                        let page_info = require(path + DS + data[i] + DS + page_list[j]);
                        let child = {
                            label: page_info.config.data.title + "(" + page_info.config.data.name + ")",
                            name: page_info.config.data.name,
                            path: data[i]
                        }

                        info.children.push(child);
                    }


                    result.push(info);
                }
            }

            return result;


        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 获取单个页面
     * @return {[type]} [description]
     */
    page_one() {
        try {

            let path = ROOT_DIR + DS + "pages" + DS + $_POST.path + DS + $_POST.name + '.json';
            if (is_dir(path)) {

                return require(path);
            } else {
                throw new Exception('页面不存在', 10001);
            }
        } catch (error) {
            throw new Exception(error);
        }
    }
    /**
     * 删除页面
     * @return {[type]} [description]
     */
    page_del() {
        try {
            let returned = new Promise((resolve, reject) => {
                fs.unlink(ROOT_DIR + DS + "pages" + DS + $_POST.path + DS + $_POST.name + '.json', (err1) => {
                    if (err1) {
                        reject(err1);
                    } else {

                        resolve(true);
                    }
                });
            })

            return returned;
        } catch (error) {
            throw new Exception(error);
        }

    }

    /**
     * 检测组件名是否可用
     * @return {[type]} [description]
     */
    component_check() {
        try {
            let path = ROOT_DIR + DS + "components" + DS + $_POST.name + '.json';
            if ($_POST.name == 'index' || is_dir(path)) {
                throw new Exception('组件名已不可用', 40001);
            } else {
                return true;
            }

        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 保存组件
     * @return {[type]} [description]
     */
    component_save() {
        try {
            let path = ROOT_DIR + DS + "components" + DS + $_POST.data.config.data.name + '.json';

            return to_mkdir(path, to_json($_POST.data), true, true);
        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 获取组件
     * @return {[type]} [description]
     */
    component_all() {
        try {
            let path = ROOT_DIR + DS + "components";
            let data = fs.readdirSync(path);
            let result = [];

            for (var i = 0; i < data.length; i++) {
                if (data[i].indexOf(".json") != -1) {
                    let component_info = require(path + DS + data[i]);
                    let info = {
                        label: component_info.config.data.title + "(" + component_info.config.data.name + ")",
                        name: component_info.config.data.name,
                    }

                    result.push(info);
                }
            }

            return result;


        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 获取单个组件
     * @return {[type]} [description]
     */
    component_one() {
        try {

            let path = ROOT_DIR + DS + "components" + DS + $_POST.name + '.json';
            if (is_dir(path)) {

                return require(path);
            } else {
                throw new Exception('组件不存在', 10001);
            }
        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 删除页面
     * @return {[type]} [description]
     */
    component_del() {
        try {
            let returned = new Promise((resolve, reject) => {
                fs.unlink(ROOT_DIR + DS + "components" + DS + $_POST.name + '.json', (err1) => {
                    if (err1) {
                        reject(err1);
                    } else {

                        resolve(true);
                    }
                });
            })

            return returned;
        } catch (error) {
            throw new Exception(error);
        }

    }


    /**
     * 检测模型是否可用
     * @return {[type]} [description]
     */
    model_check() {
        try {
            let path = ROOT_DIR + DS + "assets" + DS + "library" + DS + $_POST.name + ".js";
            if ($_POST.name == 'index' || is_dir(path)) {
                throw new Exception('模型名已不可用', 40001);
            } else {
                return true;
            }

        } catch (error) {
            throw new Exception(error);
        }
    }

    /**
     * 创建模块
     * @return {[type]} [description]
     */
    create() {
        try {
            const self = this;
            if ($_POST.data == 'invite') {
                throw new Exception('该模块不可操作', 10001);
            }
            let conf_data = copy_data($_POST.data);
            let mod_data = copy_data($_POST.data);
            if ($_POST.action == 'insert') {
                if (is_dir(ROOT_DIR + DS + "assets" + DS + "library" + DS + conf_data.name + ".js")) {
                    throw new Exception('模块已经存在不能添加', 40001);
                }
            }
            let new_field = '';
            conf_data.fields.forEach(function(value, key) {
                conf_data.fields[key].type = self.str2fun(value.type);
                new_field = conf_data.name + '_' + value.field;
                conf_data.fields[key].field = copy_data(new_field);
                mod_data.fields[key].field = copy_data(new_field);
            });
            let result1 = compile.create_config(mod_data.title, mod_data.name, mod_data.fields);
            if (result1) {
                return compile.create_model(conf_data.name, conf_data.fields);
            }
            return false;
        } catch (error) {
            throw new Exception(error);
        }
    }
    delete() {
        try {
            if ($_POST.data == 'invite') {
                throw new Exception('该模块不可操作', 10001);
            }
            let returned = new Promise((resolve, reject) => {
                fs.unlink(ROOT_DIR + DS + "assets" + DS + "library" + DS + $_POST.name + ".js", (err1) => {
                    if (err1) {
                        reject(err1);
                    } else {

                        fs.unlink(ROOT_DIR + DS + "models" + DS + $_POST.name + ".js", (err2) => {
                            if (err2) {
                                reject(err2);
                            } else {
                                resolve(true);
                            }
                        });
                    }
                });
            })

            return returned;
        } catch (error) {
            throw new Exception(error);
        }

    }

    model_all() {
        let path = ROOT_DIR + DS + "assets" + DS + "library";
        let data = fs.readdirSync(path);
        let result = [];


        data.forEach(function(value, key) {
            if (value != 'invite.js') {
                let model_info = require(path + DS + value);
                let info = {
                    label: model_info.title + "(" + model_info.name + ")",
                    name: model_info.name
                }
                result.push(info);
            }
        })

        return result;

    }
    /**
     * 获取模块列表
     * @return {[type]} [description]
     */
    async all() {
        return new Promise((resolve, reject) => {
            let path = ROOT_DIR + DS + "assets" + DS + "library";
            fs.readdir(path, function(error, data) {
                let result = [];
                if (!empty(data)) {

                    data.forEach(function(value, key) {
                        if (value != 'invite.js') {
                            let info = require(path + DS + value);
                            let new_fields = [];
                            info.fields.forEach((i, k) => {
                                if (i.field != '_uuid') {
                                    let field = copy_data(i);
                                    field.field = ltrim(field.field, info.name + '_');
                                    new_fields.push(field);
                                }
                            })
                            info['label'] = info.title + "(" + info.name + ")";
                            info.fields = new_fields;
                            result.push(info);
                        }
                    })
                }
                if (error) {
                    reject(error);
                } else {
                    resolve(result);
                }
            })
        })
    }

    /**
     * 获取单个
     * @return {[type]} [description]
     */
    first() {
        let data = $_POST;
        if (data.name == 'invite') {
            return false;
        }
        let info = require(ROOT_DIR + "/assets/library/" + data.name + ".js");
        let new_fields = [];
        info.fields.forEach((i, k) => {
            if (i.field != '_uuid') {
                let field = copy_data(i);
                field.field = ltrim(field.field, info.name + '_');
                new_fields.push(field);
            }
        })

        info.fields = new_fields;
        return info;
    }

    /**
     * 字符串转方法
     * @param  {[type]} value [description]
     * @return {[type]}       [description]
     */
    str2fun(value) {
        switch (value) {
            case 'String':
                return String;
                break;
            case 'Number':
                return Number;
                break;
            case 'Date':
                return Date;
                break;
            case 'Buffer':
                return Buffer;
                break;
            case 'Boolean':
                return Boolean;
                break;
            case 'Array':
                return Array;
                break;
            case 'Mixed':
                return Mixed;
                break;
            case 'ObjectId':
                return ObjectId;
                break;
        }
    }
}
module.exports = build;